package com.googlecode.crawlerextractor.common.dao;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityTransaction;

import org.apache.log4j.Logger;

public class Transaction {
	protected final Logger LOG = Logger.getLogger(Transaction.class);
	private EntityTransaction transaction;
	private Integer cascade = Integer.valueOf(0);

	List<String> traces = new ArrayList<String>();

	public Integer increments() {
		traces.add(Thread.currentThread().getId() + " : increments : "
				+ cascade + " " + transaction.isActive());
		cascade += 1;

		return cascade;
	}

	public Integer decrements() {
		traces.add(Thread.currentThread().getId() + " : decrements : "
				+ cascade + " " + transaction.isActive());
		if (cascade == 0) {
			LOG.error("Decrement Commit with cascade 0 : "
					+ transaction.hashCode());
			throw new RuntimeException("Can't decrement transaction if = 0");
		}

		cascade -= 1;
		return cascade;
	}

	public Integer getCascade() {
		traces.add(Thread.currentThread().getId() + " : getCascade : "
				+ cascade + " " + transaction.isActive());
		return cascade;
	}

	public Transaction(EntityTransaction entityTransaction) {
		super();
		traces.add(Thread.currentThread().getId() + " : Construct : " + cascade);
		this.transaction = entityTransaction;
	}

	public EntityTransaction getTransaction() {
		traces.add(Thread.currentThread().getId() + " : getTransaction : "
				+ cascade + " " + transaction.isActive());
		return transaction;
	}

	public void setTransaction(EntityTransaction transaction) {
		traces.add(Thread.currentThread().getId() + " : setTransaction : "
				+ cascade + " " + transaction.isActive());
		this.transaction = transaction;
	}

	public List<String> getTraces() {
		return traces;
	}

}
